from sqlalchemy import select
from forward.dependencies.database import db
from forward.model.schemas.lucky.prize import PrizeOutSchema, PrizeSchema
from forward.model.tables.activity import ActivityModel, ActivityPrizeModel, PrizeModel


class PrizeORM:
    @classmethod
    async def get_one_by_id(cls, id: int) -> PrizeOutSchema | None:
        statement = select(PrizeModel).where(PrizeModel.id == id)
        record = await db.fetch_one(statement)
        if not record:
            return None
        return PrizeOutSchema.model_validate(record, from_attributes=True)

    @classmethod
    async def get_list_by_activity_id(cls, activity_id: int) -> list[PrizeOutSchema]:
        statement = (
            select(PrizeModel)
            .select_from(PrizeModel)
            .join(ActivityPrizeModel, ActivityPrizeModel.prize_id == PrizeModel.id)
            .join(ActivityModel, ActivityModel.id == ActivityPrizeModel.activity_id)
            .where(ActivityPrizeModel.activity_id == activity_id)
            .order_by(ActivityPrizeModel.prize_index)
        )
        records = await db.fetch_all(statement)
        if not records:
            return []
        return [
            PrizeOutSchema.model_validate(record, from_attributes=True)
            for record in records
        ]
